﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using FarseerGames.FarseerPhysics;
using FarseerGames.FarseerPhysics.Mathematics;
using FarseerGames.FarseerPhysics.Dynamics;

namespace Demo1
{
  public partial class Page : UserControl
  {
    private Storyboard gameLoop;
    private PhysicsSimulator physicsSimulator;

    //Todo: Instead of PhysicsBox, we need a "base" class. 
    //But this will work for this "Getting Started" purpose.
    //This list holds all the "elements" in the game, that should be updated at the gameloop tick.
    private List<PhysicsBox> entityList = new List<PhysicsBox>();

    public Page()
    {
      //Default Component Initializer created by VS2008, just leave it :)
      InitializeComponent();

      //Setup GameLoop
      gameLoop = new Storyboard();
      gameLoop.Completed += new EventHandler(gameLoop_Completed);
      gameLoop.Duration = TimeSpan.FromMilliseconds(25); //The game will be updated every 25 millisecond
      this.Resources.Add("gameloop", gameLoop);
      this.Loaded += new RoutedEventHandler(Page_Loaded);

      //Setup PhysicsSimulator and add gravity in the Y direction (down) with a value of 150
      physicsSimulator = new PhysicsSimulator(new Vector2(0, 150));

      //Add our PhysicsBox (PhysicsElement, Sprite, what ever you wanna call it)
      PhysicsBox box = new PhysicsBox(128, 128, 100);
      box.Body.Position = new Vector2((float)this.Width / 2, (float)this.Height / 2);

      //Add the Body of our PhysicsBox to the physicsSimulator
      physicsSimulator.Add(box.Body);
      //Add the actual PhysicsBox(UserControl) object to the list of UserControls to be updated in the gameloop event
      entityList.Add(box);
      //Finally we add the PhysicsBox (UserControl) to the actual canvas where we want it to be rendered, so we can actually see it :)
      this.DrawingCanvas.Children.Add(box);
    }

    protected void Page_Loaded(object sender, RoutedEventArgs e)
    {
      //This will start the actual gameloop - this is where your application actually starts (from the users point of view)
      //And before you ask, no, this can't be done from the constructor :)
      gameLoop.Begin();
    }

    protected void gameLoop_Completed(object sender, EventArgs e)
    {
      physicsSimulator.Update(.01f);

      foreach (PhysicsBox box in entityList)
      {
        box.Update();
      }

      gameLoop.Begin();
    }
  }
}
